from flask import Blueprint, request, jsonify, session
from models import db
from models.ScoreWeight import ScoreWeight
from models.Company import Company
from decimal import Decimal

score_weight_bp = Blueprint('score_weight', __name__)

@score_weight_bp.route('/score-weights', methods=['GET'])
def get_score_weights():
    """获取当前公司的分数权重"""
    if 'user_id' not in session or session['role'] != 'company':
        return jsonify({'error': '未授权访问'}), 401
    
    # 先获取公司信息
    company = Company.query.filter_by(user_id=session['user_id']).first()
    if not company:
        return jsonify({'error': '未找到公司信息'}), 404
    
    weights = ScoreWeight.query.filter_by(company_id=company.company_id).first()
    
    if not weights:
        return jsonify({
            'technical_weight': 0.40,
            'learning_weight': 0.20,
            'team_weight': 0.15,
            'problem_solving_weight': 0.15,
            'communication_weight': 0.10
        })
    
    return jsonify({
        'technical_weight': float(weights.technical_weight),
        'learning_weight': float(weights.learning_weight),
        'team_weight': float(weights.team_weight),
        'problem_solving_weight': float(weights.problem_solving_weight),
        'communication_weight': float(weights.communication_weight)
    })

@score_weight_bp.route('/score-weights', methods=['POST', 'PUT'])
def update_score_weights():
    """更新或创建分数权重"""
    if 'user_id' not in session or session['role'] != 'company':
        return jsonify({'error': '未授权访问'}), 401
    
    # 先获取公司信息
    company = Company.query.filter_by(user_id=session['user_id']).first()
    if not company:
        return jsonify({'error': '未找到公司信息'}), 404
    
    data = request.json
    
    # 验证权重总和是否为1
    total_weight = sum(float(data.get(k, 0)) for k in [
        'technical_weight', 'learning_weight', 'team_weight',
        'problem_solving_weight', 'communication_weight'
    ])
    
    if abs(total_weight - 1.0) > 0.001:  # 允许小误差
        return jsonify({'error': '所有权重之和必须等于1'}), 400
    
    weights = ScoreWeight.query.filter_by(company_id=company.company_id).first()
    
    if not weights:
        weights = ScoreWeight(company_id=company.company_id)
        db.session.add(weights)
    
    # 更新权重
    weights.technical_weight = Decimal(str(data.get('technical_weight', 0.40)))
    weights.learning_weight = Decimal(str(data.get('learning_weight', 0.20)))
    weights.team_weight = Decimal(str(data.get('team_weight', 0.15)))
    weights.problem_solving_weight = Decimal(str(data.get('problem_solving_weight', 0.15)))
    weights.communication_weight = Decimal(str(data.get('communication_weight', 0.10)))
    
    try:
        db.session.commit()
        return jsonify({'message': '权重更新成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500 